package com.zzyy.study.aop;

import com.github.pagehelper.PageHelper;
import com.zzyy.study.common.IPageQuery;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @auther zzyy
 * @create 2024-06-26 0:15
 */
@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class PageQueryAspect {

    /**
     * 容器捞鱼V2，方法参数捞
     * 拦截mapper中的所有方法，重点看传入的参数是否是我们定义的IPageQuery接口的实现子类
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.zzyy.study.mapper.*Mapper.*(..))") //com.zzyy.study.mapper.UserMapper
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        boolean pageFlag = false;
        try {
            /**
             * UserMapper接口里面定义的方法
             *      List<User> selectPageHelperAOP(PageQuery pageQuery);
             *
             * 遍历方法参数，如果含有IPageQuery接口的实现子类，则从参数中取出使用PageHelper前置通知加强开启分页
             */
            Object[] args = proceedingJoinPoint.getArgs();
            //取出全部参数，逐个判断是否是IPageQuery接口的实现子类
            for (Object arg : args) {
                if (arg instanceof IPageQuery) {
                    IPageQuery pageQuery = (IPageQuery) arg;
                    //如果是IPageQuery接口的实现子类，前置通知加强开启分页
                    PageHelper.startPage(pageQuery.getPageNum(), pageQuery.getPageSize(), pageQuery.count());
                    pageFlag = true;
                    break;
                }
            }
            return proceedingJoinPoint.proceed();//通过放行
        } finally {
            if (pageFlag) {
                PageHelper.clearPage();//清理分页信息
            }
        }
    }
}
